<?php

namespace App\Http\Controllers\SystemManagement;

use App\Http\Controllers\IndexController;
use App\Models\SystemManagement\Privilege;
use App\Models\SystemManagement\PrivilegeFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class PrivilegeController
 * @package App\Http\Controllers\SystemManagement
 * @group 权限管理
 */
class PrivilegeController extends IndexController
{
    /**
     * 新增权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam parent_id int required 父级ID
     * @bodyParam name string required 权限名称
     * @bodyParam method string required 请求方式get post put delete
     * @bodyParam route string required 权限路由
     * @bodyParam menu char required 1 作为菜单显示; 0 不显示
     * @bodyParam type char required 权限类型 0:h5页面 1:接口权限
     * @bodyParam level char required 权限的限制级别 0:不验证 1:仅需要登录 2.需要赋予权限
     * @bodyParam status char required 权限状态 1 启用; 0 禁用
     * @bodyParam description text 权限描述
     * @bodyParam sort int 菜单排序(降序)
     * @bodyParam privilege_ids string 图标附件ids:1,2,3
     *
     * @response 201 {"code":201,"msg":"created","data":"成功"}
     * @response 400 {"code":400,"msg":"parameter error","data":"失败"}
     */
    public function createPrivilege(\App\Http\Requests\System\Privilege $request){
        DB::beginTransaction();
        try {
            $data = $request->all();
            $privilege = Privilege::create($data);
            if($request->has('privilege_ids')){
                $file_data = [];
                $fileArr = explode(',',$request->get('privilege_ids'));
                foreach ($fileArr as $k=>$value){
                    $tmp = [];
                    $tmp['file_id'] = $value;
                    $tmp['privilege_id'] = $privilege->id;
                    array_push($file_data,$tmp);
                }
                try{
                    PrivilegeFile::insert($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
            }
            DB::commit();
            return response()->json(encodeMsg($privilege,201));
        } catch (QueryException $e) {
            DB::rollBack();
            // dd($e);
            return response()->json(encodeMsg(['message' => '添加失败!'],400));
        }
    }

    /**
     * 权限列表--带分页
     * @return false|string
     *
     * @bodyParam parent_id int required 父级ID
     * @bodyParam name string required 权限名称
     * @bodyParam route string required 权限路由
     * @bodyParam menu char required 1 作为菜单显示; 0 不显示
     * @bodyParam status char required 权限状态 1 启用; 0 禁用
     *
     * @queryParam parent_id int required 父级ID
     * @queryParam name string required 权限名称
     * @queryParam method string required 请求方式get post put delete
     * @queryParam route string required 权限路由
     * @queryParam menu char required 1 作为菜单显示; 0 不显示
     * @queryParam type char required 权限类型 0:h5页面 1:接口权限
     * @queryParam level char required 权限的限制级别 0:不验证 1:仅需要登录 2.需要赋予权限
     * @queryParam status char required 权限状态 1 启用; 0 禁用
     * @queryParam description text required 权限描述
     * @queryParam sort int required 菜单排序(降序)
     * @queryParam files->file->local_url string 附件url地址
     *
     * @response 200 {"code":201,"msg":"success","data":"成功"}
     * @response 404 {"code":404,"msg":"not found","data":"没有查询到任何数据"}
     */
    public function getPrivilege(Request $request){
        // $per_page = request()->input('per_page');
        return $this->getList(new Privilege(),$request);
    }

    /**
     * 权限列表 -- 不带分页
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam parent_id int required 父级ID
     * @bodyParam name string required 权限名称
     * @bodyParam route string required 权限路由
     * @bodyParam menu char required 1 作为菜单显示; 0 不显示
     * @bodyParam status char required 权限状态 1 启用; 0 禁用
     *
     * @queryParam parent_id int required 父级ID
     * @queryParam name string required 权限名称
     * @queryParam method string required 请求方式get post put delete
     * @queryParam route string required 权限路由
     * @queryParam menu char required 1 作为菜单显示; 0 不显示
     * @queryParam type char required 权限类型 0:h5页面 1:接口权限
     * @queryParam level char required 权限的限制级别 0:不验证 1:仅需要登录 2.需要赋予权限
     * @queryParam status char required 权限状态 1 启用; 0 禁用
     * @queryParam description text required 权限描述
     * @queryParam sort int required 菜单排序(降序)
     * @queryParam files->file->local_url string 附件url地址
     *
     * @response 200 {"code":201,"msg":"success","data":"成功"}
     * @response 404 {"code":404,"msg":"not found","data":"没有查询到任何数据"}
     */
    public function getAll(Request $request){
        $privilege =  Privilege::getAll($request);
        $parent_id = $request->input('parent_id', 0);
        $lists = generateTree($privilege,$parent_id);
        return response()->json(encodeMsg($lists,200));
    }


    /**
     * 查看权限
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id int required 此权限ID
     *
     * @queryParam parent_id int required 父级ID
     * @queryParam name string required 权限名称
     * @queryParam method string required 请求方式get post put delete
     * @queryParam route string required 权限路由
     * @queryParam menu char required 1 作为菜单显示; 0 不显示
     * @queryParam type char required 权限类型 0:h5页面 1:接口权限
     * @queryParam level char required 权限的限制级别 0:不验证 1:仅需要登录 2.需要赋予权限
     * @queryParam status char required 权限状态 1 启用; 0 禁用
     * @queryParam description text required 权限描述
     * @queryParam sort int required 菜单排序(降序)
     * @queryParam files->file->local_url string 附件url地址
     *
     * @response 200 {"code":201,"msg":"success","data":"成功"}
     * @response 404 {"code":404,"msg":"not found","data":"没有该记录"}
     */
    public function getOnePrivilege($id){
        $data = Privilege::with('files')->find($id);
        if($data == []) {
            return response()->json(encodeMsg(["message" => "没有该记录!"], 404));
        } else {
            return response()->json(encodeMsg($data,200));
        }
    }

    /**
     * 修改权限
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam id int required 此权限ID
     * @bodyParam parent_id int required 父级ID
     * @bodyParam name string required 权限名称
     * @bodyParam method string required 请求方式get post put delete
     * @bodyParam route string required 权限路由
     * @bodyParam menu char required 1 作为菜单显示; 0 不显示
     * @bodyParam type char required 权限类型 0:h5页面 1:接口权限
     * @bodyParam level char required 权限的限制级别 0:不验证 1:仅需要登录 2.需要赋予权限
     * @bodyParam status char required 权限状态 1 启用; 0 禁用
     * @bodyParam description text required 权限描述
     * @bodyParam sort int required 菜单排序(降序)
     * @bodyParam privilege_ids string 图标附件ids:1,2,3
     *
     * @response 205 {"code":205,"msg":"updated","data":"成功"}
     * @response 400 {"code":400,"msg":"parameter error","data":"失败"}
     */
    public function updatePrivilege(\App\Http\Requests\System\Privilege $request,$id){
        return $this->update($request,$id,new Privilege());
        $privilege = Privilege::find($id);
        if($privilege == []) {
            return response()->json(encodeMsg(["message" => "没有该市政部件信息!"], 404));
        }
        DB::beginTransaction();
        try {
            $data = $request->all();
            if($request->has('privilege_ids')){
                $origin_files = PrivilegeFile::where('privilege_id',$id)->get()->toArray();//图片原来的id号是好多 取出
                $origin_file_ids = array();//这个数组用于报错以前的所有file的id号
                if($origin_files != []){
                    foreach ($origin_files as $v){
                        array_push($origin_file_ids,$v['id']);
                    }
                }
                $file_data = [];
                $fileArr = explode(',',$request->get('privilege_ids'));
                foreach ($fileArr as $k=>$value){
                    $tmp = [];
                    $tmp['file_id'] = $value;
                    $tmp['privilege_id'] = $id;
                    array_push($file_data,$tmp);
                }
                try{
                    PrivilegeFile::whereIn('id',$origin_file_ids)->delete();
                    PrivilegeFile::insert($file_data);
                }catch (\Exception $e){
                    DB::rollBack();
                    return response()->json(encodeMsg(["message" => "请先确认图片是否已经添加或者图片id是否重复".$e->getMessage()],404), 404);
                }
            }
            $privilege->update($data);
            DB::commit();
            return response()->json(encodeMsg($privilege,200));
        } catch (QueryException $e) {
            DB::rollBack();
            return response()->json(encodeMsg(['message' => '修改失败!'],400));
        }
    }

    /**
     * 批量删除权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     *
     * @bodyParam ids array 权限ID,批量删除+单条删除,以数组形式
     *
     * @response  204 {"code":204,"msg":"deleted","data":"删除成功"}
     * @response  400 {"code":400,"msg":"failed","data":"删除失败/数据格式错误"}
     */
    public function del(Request $request){
        return $this->delete($request,new Privilege());
    }

    /**
     * 批量恢复权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam ids array 权限ID,批量恢复+单条恢复,以数组形式
     *
     * @response  204 {"code":204,"msg":""deleted,"data":"恢复成功"}
     * @response  400 {"code":400,"msg":"failed","data":"恢复失败/数据格式错误"}
     */
    public function rec(Request $request){
        return $this->recover($request,new Privilege());
    }

    /**
     * 搜索权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     *
     * @bodyParam name 权限名称
     *
     * @queryParam parent_id int required 父级ID
     * @queryParam name string required 权限名称
     * @queryParam method string required 请求方式get post put delete
     * @queryParam route string required 权限路由
     * @queryParam menu char required 1 作为菜单显示; 0 不显示
     * @queryParam type char required 权限类型 0:h5页面 1:接口权限
     * @queryParam level char required 权限的限制级别 0:不验证 1:仅需要登录 2.需要赋予权限
     * @queryParam status char required 权限状态 1 启用; 0 禁用
     * @queryParam description text required 权限描述
     * @queryParam sort int required 菜单排序(降序)
     * @queryParam files->file->local_url string 附件url地址
     *
     * @response 200 {"code":201,"msg":"success","data":"成功"}
     * @response 404 {"code":404,"msg":"not found","data":"没有该记录"}
     */
    public function getBy(Request $request){
        $con = $request->all();
        return $this->getByCond($con,new Privilege());
    }

    /**
     * 获取所有的路由，用户提示信息
     * @return mixed
     */
    public function allRoutes()
    {
        $routes = app()->routes->getRoutes();
        $data = [];
        foreach ($routes as $value) {
            if(!$value->uri || $value->uri === '/') {
                continue;
            }
            $data[] = $value->uri;
        }

        return response()->json(encodeMsg($data,200));
    }

}
